package com.panopset.flywheel;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author Karl Dinwiddie
 */
public class CommandText extends Command {

    private String text;

    public CommandText(Template template, String params) {
        super(template);
        assert params != null;
        this.text = params;
    }

    @Override
    public String getDescription() {
        StringReader sr = new StringReader(text);
        BufferedReader br = new BufferedReader(sr);
        try {
            String s = br.readLine();
            return s == null ? "" : s;
        } catch (IOException e) {
            return e.getMessage();
        } finally {
            try {
                br.close();
            } catch (IOException ex) {
                Logger.getLogger(CommandText.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    @Override
    public void resolve(StringWriter sw) {
        String rtn = text;
        if (!template.flywheel.isReplacementsSuppressed) {
            for (String[] s : template.flywheel.getReplacements()) {
                rtn = rtn.replace(s[0], s[1]);
            }
        }
        sw.append(rtn);
    }
}
